package elitech.vietnam.weatherfashion;

import java.io.File;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;

import elitech.vietnam.weatherfashion.backgroundtask.NotificationBackGroundService;
import elitech.vietnam.weatherfashion.backgroundtask.ReloadDataService;
import elitech.vietnam.weatherfashion.backgroundtask.ReloadWeatherService;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dialog.ConfirmDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.Notify;
import elitech.vietnam.weatherfashion.notification.GCMIntentService;
import elitech.vietnam.weatherfashion.notification.NotificationPopupWindow;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.BaseContainerFragment;
import elitech.vietnam.weatherfashion.tabs.SelfContainerFragment;
import elitech.vietnam.weatherfashion.tabs.SettingsContainerFragment;
import elitech.vietnam.weatherfashion.tabs.StylerContainerFragment;
import elitech.vietnam.weatherfashion.tabs.TodayContainerFragment;
import elitech.vietnam.weatherfashion.tabs.WeeklyContainerFragment;
import elitech.vietnam.weatherfashion.tabs.self.SelfPostFragment;
import elitech.vietnam.weatherfashion.tabs.settings.EditProfileFragment;
import elitech.vietnam.weatherfashion.tabs.settings.SettingsFragment;
import elitech.vietnam.weatherfashion.tabs.styler.StylerDetailFragment;
import elitech.vietnam.weatherfashion.tabs.styler.StylerPostFragment;
import elitech.vietnam.weatherfashion.ultilities.Utilities;
import elitech.vietnam.weatherfashion.ultilities.ValueOption;
import elitech.vietnam.weatherfashion.widget.NotifyButton;
import eu.janmuller.android.simplecropimage.CropImage;

public class MainActivity extends FragmentActivity implements FragmentTabHost.OnTabChangeListener {

	public static final String	TAB_TODAY						= "TF";
	public static final String	TAB_WEEKLY						= "WF";
	public static final String	TAB_STYLER						= "TS";
	public static final String	TAB_SELF						= "MF";
	public static final String	TAB_SETTINGS					= "ST";

	public static final int		REQ_CODE_LIB					= 10;
	public static final int		REQ_CODE_CAM					= 11;
	public static final int		REQ_CODE_SETTING_RELOAD_WEATHER	= 112;
	public static final int		REQ_CODE_SETTING_CODE			= 113;
	public static final int		REQ_CODE_EDIT_PROFILE_ALBUM		= 114;
	public static final int		REQ_CODE_EDIT_PROFILE_CAMERA	= 115;
	public static final int		REQ_CODE_EDIT_PROFILE_CROP		= 116;
	public static final int		REQ_CODE_EDITPOST				= 12;
	public static final int		REQ_CODE_NEWPOST				= 13;
	public static final int		REQ_CODE_LOGIN					= 14;

	private FragmentTabHost		mTabHost;
	private Intent				intentReloadWeatherService;
	private Intent				intentReloadDataService;

	private NotifyButton		mNotifyButton;
	public NotificationPopupWindow	mNotiWindow;

	// public NotificationPopupWindow mNotiWindow;

	int							currTab							= 0;
	boolean						isBackclicked					= false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		Utils.printDeviceScreenType(this);
		initView();
		// onNotificationArrived(getIntent());
	}

	@Override
	protected void onResume() {
		Log.w("MainActivity", "onResume");

		super.onResume();
		// Start service reload data
		intentReloadDataService = new Intent(this, ReloadDataService.class);
		startService(intentReloadDataService);
		// //////////////////

		// Start service reload weather
		intentReloadWeatherService = new Intent(this, ReloadWeatherService.class);
		startService(intentReloadWeatherService);
		// /
		registerReceiver(mNotiReceiver, new IntentFilter(Const.ACTION_INCREASE_BADGE));

		ValueOption option = GlobalValue.getInstance(this).readOptionInfo();
		Utils.Log("onResume() Mainactivity + NotificationBackGroundService2.isRunning=" + NotificationBackGroundService.isRunning);

		Utils.Log("LanguageIndex " + option.getLanguageIndex());
		Utils.Log("LanguageCode " + option.getLanguageCode());

		if (option.getLanguageIndex() == 0) {
			option.setLanguageCode(Utilities.convertCountryCodeToLanguageCode(Const.COUNTRY_CODE));
		}

		Utilities.changeConfigLanguage(this, option.getLanguageCode());

		Intent intent = getIntent();
		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				boolean isReload = intent.getBooleanExtra(SettingsFragment.SETTING_RELOAD, false);
				intent.removeExtra(SettingsFragment.SETTING_RELOAD);
				if (isReload) {
					currTab = 4;
					mTabHost.setCurrentTab(currTab);
				}
			}
		}

		/**
		 * Temporary method to display notification
		 */
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				openNotification(getIntent());
			}
		}, 1000);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// stop reload data
		unregisterReceiver(mNotiReceiver);
		stopService(intentReloadDataService);
		// stop reload weather service
		stopService(intentReloadWeatherService);
	}

	private void initView() {
		mNotiWindow = new NotificationPopupWindow(this);

		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

		mTabHost.addTab(mTabHost.newTabSpec(TAB_TODAY).setIndicator(createTabView(R.drawable.ic_today, R.drawable.maintabview_today)),
				TodayContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_WEEKLY).setIndicator(createTabView(R.drawable.ic_weekly, R.drawable.maintabview_weekly)),
				WeeklyContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_STYLER).setIndicator(createTabView(R.drawable.ic_styler, R.drawable.maintabview_styler)),
				StylerContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_SELF).setIndicator(createTabView(R.drawable.ic_self, R.drawable.maintabview_self)),
				SelfContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_SETTINGS).setIndicator(createTabView(R.drawable.ic_settings, R.drawable.maintabview_setting)),
				SettingsContainerFragment.class, null);

		mTabHost.setOnTabChangedListener(this);

		for (int i = 0; i < mTabHost.getTabWidget().getTabCount(); i++) {
			final int index = i;
			mTabHost.getTabWidget().getChildAt(i).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mTabHost.getCurrentTab() != index)
						mTabHost.setCurrentTab(index);
					else
						popAllTabFragment();
				}
			});
		}

	}

	@Override
	public void onBackPressed() {
		boolean isPopFragment = false;
		BaseContainerFragment base = getCurrentBase();
		if (base != null)
			isPopFragment = base.popFragment();
		String currentTabTag = mTabHost.getCurrentTabTag();

		if (!isPopFragment && !currentTabTag.equals(TAB_TODAY))
			mTabHost.setCurrentTab(0);

		if (!isPopFragment && currentTabTag.equals(TAB_TODAY)) {
			if (isBackclicked) {
				// Intent intent = new Intent(MainActivity.this,
				// NotificationBackGroundService.class);
				// stopService(intent);
				finish();
			} else {
				isBackclicked = true;
				Toast.makeText(this, getString(R.string.click_back_again_to_exit), Toast.LENGTH_SHORT).show();
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						isBackclicked = false;
					}
				}, 2000);
			}
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Log.w("Main Activity", "onNewIntent");
		super.onNewIntent(intent);
		openNotification(intent);
	}

	private View createTabView(int resId, int bgId) {
		View view = LayoutInflater.from(this).inflate(R.layout.tab_mainitem, null);
		view.setBackgroundResource(bgId);
		ImageView item_image = (ImageView) view.findViewById(R.id.tab_item_image);
		item_image.setImageResource(resId);
		return view;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		int n = requestCode & 0xffff;
		if (resultCode != RESULT_OK)
			return;

		Intent intent;
		Uri uri;

		switch (n) {
		case REQ_CODE_EDIT_PROFILE_CROP:
			EditProfileFragment.THIS.onActivityResult(requestCode, resultCode, data);
			break;
		
		case REQ_CODE_EDIT_PROFILE_ALBUM:
			String path = getRealPathFromURI(data.getData());
			if (path == null) {
				Toast.makeText(this, getString(R.string.invalidimage), Toast.LENGTH_SHORT).show();
				return;
			}
			uri = Uri.fromFile(new File(path));
			intent = new Intent(this, CropImage.class);
			
			intent.putExtra(CropImage.IMAGE_PATH, uri.getPath());
			intent.putExtra(CropImage.SCALE, true);
			intent.putExtra(CropImage.ASPECT_X, 1);
			intent.putExtra(CropImage.ASPECT_Y, 1);

			startActivityForResult(intent, REQ_CODE_EDIT_PROFILE_CROP);
			break;

		case REQ_CODE_EDIT_PROFILE_CAMERA:
			uri = Uri.fromFile(new File(NewPostActivity.CAM_PATH));
			intent = new Intent(this, CropImage.class);

			intent.putExtra(CropImage.IMAGE_PATH, uri.getPath());
			intent.putExtra(CropImage.SCALE, true);
			intent.putExtra(CropImage.ASPECT_X, 1);
			intent.putExtra(CropImage.ASPECT_Y, 1);

			startActivityForResult(intent, REQ_CODE_EDIT_PROFILE_CROP);
			break;

		case REQ_CODE_SETTING_CODE:
			SettingsFragment.THIS.onActivityResult(requestCode, resultCode, data);
			break;

		case REQ_CODE_SETTING_RELOAD_WEATHER:
			SettingsFragment.THIS.onActivityResult(requestCode, resultCode, data);
			break;

		case REQ_CODE_LIB:
			intent = new Intent(MainActivity.this, NewPostActivity.class);
			intent.putExtra("image", Utils.getPath(data.getData(), this));
			intent.putExtra("request", REQ_CODE_LIB);
			startActivityForResult(intent, REQ_CODE_NEWPOST);
			break;

		case REQ_CODE_CAM:

			Utils.Log(WFApplication.getInstance().todayData == null);
			intent = new Intent(MainActivity.this, NewPostActivity.class);
			intent.putExtra("image", NewPostActivity.CAM_PATH);
			intent.putExtra("request", REQ_CODE_CAM);
			startActivityForResult(intent, REQ_CODE_NEWPOST);
			break;

		case REQ_CODE_NEWPOST:
			getIntent().putExtra("SELF_RELOAD", 1);
			WFApplication.getInstance().stylerAllData = null;
			break;

		case REQ_CODE_LOGIN:
			getIntent().putExtra("SELF_RELOAD", 1);
			break;

		case REQ_CODE_EDITPOST:
			if (data.getBooleanExtra("EditPostResult", false)) {
				getIntent().putExtra("SELF_RELOAD", 1);
				getIntent().putExtra("POST_RELOAD", 1);
				WFApplication.getInstance().stylerAllData = null;
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onTabChanged(String tabId) {
		MemberDTO user = GlobalValue.getInstance(getApplicationContext()).readUserInfo();
		if (tabId.equals(TAB_SELF) && (user == null)) {
			new ConfirmDialog.Builder(this).setMessage(getString(R.string.request_login)).setYesClick(new ConfirmDialog.OnYesClick() {
				@Override
				public void doClick() {
					Intent intent = new Intent(MainActivity.this, LoginActivity.class);
					startActivityForResult(intent, REQ_CODE_LOGIN);
				}
			}).setNoClick(new ConfirmDialog.OnNoClick() {
				@Override
				public void doClick() {
					mTabHost.setCurrentTab(currTab);
				}
			}).build().show();
		} else {
			currTab = mTabHost.getCurrentTab();
		}
		if (tabId.equals(TAB_TODAY))
			getIntent().putExtra("TODAY_FIRST_PAGE", 1);

		if (tabId.equals(TAB_WEEKLY))
			getIntent().putExtra("WEEKLY_FIRST_TAB", 1);

		if (tabId.equals(TAB_STYLER))
			getIntent().putExtra("STYLER_FIRST_TAB", 1);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private boolean popAllTabFragment() {
		BaseContainerFragment base = getCurrentBase();
		if (base != null)
			return base.popAllFragment();
		return false;
	}

	public BaseContainerFragment getCurrentBase() {
		String currentTabTag = mTabHost.getCurrentTabTag();
		BaseContainerFragment base = null;
		try {
			if (currentTabTag.equals(TAB_TODAY)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_TODAY));
			} else if (currentTabTag.equals(TAB_WEEKLY)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_WEEKLY));
			} else if (currentTabTag.equals(TAB_STYLER)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_STYLER));
			} else if (currentTabTag.equals(TAB_SELF)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_SELF));
			} else if (currentTabTag.equals(TAB_SETTINGS)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_SETTINGS));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return base;
	}

	private void openNotification(final Intent intent) {
		if (mNotiWindow.isShowing())
			mNotiWindow.dismiss();
		Bundle extras = intent.getExtras();
		if (extras != null && extras.containsKey(GCMIntentService.DATA_TAG) && !extras.getString(GCMIntentService.DATA_TAG).equals("")) {
			Log.w("Push Notification", "has " + GCMIntentService.DATA_TAG + " extra");
			WFApplication.getInstance().mBadge.increaseBadge(-1);
			final Notify noti = new Gson().fromJson(extras.getString(GCMIntentService.DATA_TAG), Notify.class);
			for (Notify n : WFApplication.getInstance().mListNoti) {
				if (n.Id == noti.Id) {
					WFApplication.getInstance().mListNoti.remove(n);
					break;
				}
			}
			new AsyncTask<Integer, Integer, Boolean>() {
				@Override
				protected Boolean doInBackground(Integer... params) {
					PHPSoapServiceCaller service = new PHPSoapServiceCaller();
					try {
						service.readNotification(noti.Id);
					} catch (IOException e) {}
					return true;
				}
			}.execute();
			BaseContainerFragment base = getCurrentBase();
			Log.w("Notify", "Base: " + ((base == null) ? "null" : "have instance"));
			if (base != null) {
				Fragment fragment = null;
				if (noti.Type == 1) {
					fragment = SelfPostFragment.init(noti.PostID);
				}
				if (noti.Type == 2) {
					fragment = StylerPostFragment.init(noti.PostID);
				}
				if (noti.Type == 3) {
					fragment = StylerPostFragment.init(noti.PostID);
				}
				if (noti.Type == 4) {
					fragment = StylerDetailFragment.init(noti.SenderID);
				}
				base.getChildFragmentManager()
						.beginTransaction()
						.setCustomAnimations(R.anim.fragment_slidein_left, R.anim.fragment_slideout_right, R.anim.fragment_slidein_right,
								R.anim.fragment_slideout_left).addToBackStack(base.getTag())
						.replace(R.id.container_framelayout, fragment, fragment.getClass().getName()).commitAllowingStateLoss();
			}
			intent.removeExtra(GCMIntentService.DATA_TAG);
			GCMIntentService.NUMBER = 0;
		}
	}

	public void setCurrentNotifyButton(NotifyButton button) {
		this.mNotifyButton = button;
		mNotifyButton.setNumber(((WFApplication) getApplicationContext()).mBadge.mBadgeCount);
	}
	
	public String getRealPathFromURI(Uri contentUri) {
		String path = null;
		String[] proj = { MediaStore.MediaColumns.DATA };
		Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
		if (cursor.moveToFirst()) {
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
			path = cursor.getString(column_index);
		}
		cursor.close();
		return path;
	}

	private BroadcastReceiver	mNotiReceiver	= new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (mNotifyButton != null) {
				Log.w("Increase Badge", "Receive Broadcast NOT NULL");
				WFApplication.getInstance().mHideLocalNoti = false;
				mNotifyButton.setNumber(((WFApplication) getApplicationContext()).mBadge.mBadgeCount);
			}
		}
	};
}
